const bcrypt = require('bcryptjs')
const Router = require('koa-router')

const { 
    RegisterValidator,
    EmailCodeValidaor,
    LoginValidator,
    RefreshTokenValidator
} = require('../../../validators/user')
const { User } = require('../../../models/make/user')

const { sendEmail } = require('../../../services/sendEmail')

const Exception = require('../../../../core/exception')

const { getTokens, tokenRequired, verifyRefreshToken } = require('../../../../core/jwt')

const {
    getUid,
    getClientIP,
    getNowTime
  } = require('../../../../core/util')
const router = new Router({
    prefix: '/make/v1/user'
})

/**
 * @api {post} /make/v1/user/register 注册
 * @apiGroup 客户端用户
 * @apiVersion 1.0.0
 * 
 * @apiParam {String} nick_name 昵称
 * @apiParam {String} email 邮箱
 * @apiParam {String} password 密码
 * @apiParam {String} againPassword 确认密码
 * @apiParam {String} code 邮箱验证码
 * 
 * @apiSuccessExample  {json} 请求成功
 * {
 *   "errCode": 0,
 *   "errMsg": "注册成功"
 * }
 */
router.post('/register', async ctx => {
    const v = await new RegisterValidator().validate(ctx)
    const user = {
        uid: getUid(),
        email: v.get('body.email'),
        password: v.get('body.password'),
        nick_name: v.get('body.nick_name'),
        ip: getClientIP(ctx.req),
        user_type: 1
    }
    await User.create(user)
    ctx.success({ errMsg: '注册成功' })
})

/**
 * @api {post} /make/v1/user/email 发送邮箱验证码
 * @apiGroup 客户端用户
 * @apiVersion 1.0.0
 * 
 * @apiParam {String} nick_name 昵称
 * @apiParam {String} email 邮箱
 * 
 * @apiSuccessExample  {json} 请求成功
 * {
 *   "errCode": 0,
 *   "errMsg": "验证码发送成功，请注意查收"
 * }
 */
router.post('/email', async ctx => {
    const v = await new EmailCodeValidaor().validate(ctx)
    const res = await sendEmail(v.get('body.nick_name'), v.get('body.email'))
    if (res === 'OK') {
        ctx.success({ errMsg: '验证码发送成功，请注意查收' })
    }
})
/**
 * @api {post} /make/v1/user/login 登录
 * @apiGroup 客户端用户
 * @apiVersion 1.0.0
 * 
 * @apiParam {String} email 邮箱
 * @apiParam {String} password 密码
 * @apiParam {String} code 邮箱验证码
 * 
 * @apiSuccessExample  {json} 请求成功
 * {
 *   "errCode": 0,
 *   "errMsg": "ok",
 *   "data": {
 *      "accessToken": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
 *      "refreshToken": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 *   }
 * }
 */
router.post('/login', async ctx => {
    const v = await new LoginValidator().validate(ctx)
    const user = await User.verifyEmailPassword(ctx, v.get('body.email'), v.get('body.password'), v.get('body.code'))
    user.last_at = getNowTime(Date.now())
    user.save()
    const { accessToken, refreshToken } = getTokens(user);
    ctx.json({ accessToken, refreshToken })
})

/**
 * @api {get} /make/v1/user/getUserInfo 获取用户信息
 * @apiGroup 客户端用户
 * @apiVersion 1.0.0
 * @apiHeader {String} Authorization Authorization 的 Type 为 Bearer，格式 `Bearer accessToken`
 * 
 * @apiSuccessExample  {json} 请求成功
 * {
 *   "errCode": 0,
 *   "errMsg": "ok",
 *   "data": {
 *      "uid": "2003212058226615552",
 *      "email": "6125440@qq.com",
 *      "nick_name": "启航",
 *      "head_img": "",
 *      "sex": 0,
 *      "post_job": "",
 *      "address": "",
 *      "introduction": "",
 *      "status": 1,
 *      "grade": 1,
 *      "user_type": 1,
 *      "last_at": "2020-03-22 01:10:22",
 *      "remark": "",
 *      "integral": 0,
 *      "mobile": "",
 *      "created_at": "2020-03-21 20:58:22"
 *   }
 * }
 */
router.get('/getUserInfo', tokenRequired, async ctx => {
    ctx.json(ctx.userInfo)
})

/**
 * @api {post} /make/v1/user/refreshToken 获取新的accessToken
 * @apiGroup 客户端用户
 * @apiVersion 1.0.0
 * 
 * @apiParam {String} refresh_token 刷新token令牌
 * 
 * @apiSuccessExample  {json} 请求成功
 * {
 *   "errCode": 0,
 *   "errMsg": "ok",
 *   "data": {
 *      "accessToken": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
 *      "refreshToken": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 *   }
 * }
 */
router.post('/refreshToken', async ctx => {
    const v = await new RefreshTokenValidator().validate(ctx)
    const obj = verifyRefreshToken(v.get('body.refresh_token'))
    const { accessToken, refreshToken } = getTokens({ uid: obj.identity });
    ctx.json({ accessToken, refreshToken })
})

module.exports = router
